/**
 * 安全相关的工具函数
 */

// XSS防护 - HTML转义
export function escapeHtml(unsafe: string): string {
  return unsafe
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}

// 清理用户输入
export function sanitizeInput(input: string): string {
  return input
    .trim()
    .replace(/[<>]/g, '') // 移除潜在的HTML标签
    .substring(0, 1000); // 限制长度
}

// 验证邮箱格式
export function isValidEmail(email: string): boolean {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

// 验证密码强度
export interface PasswordStrength {
  isValid: boolean;
  score: number; // 0-4
  feedback: string[];
}

export function validatePassword(password: string): PasswordStrength {
  const feedback: string[] = [];
  let score = 0;

  if (password.length < 8) {
    feedback.push('密码至少需要8个字符');
  } else {
    score += 1;
  }

  if (!/[a-z]/.test(password)) {
    feedback.push('密码需要包含小写字母');
  } else {
    score += 1;
  }

  if (!/[A-Z]/.test(password)) {
    feedback.push('密码需要包含大写字母');
  } else {
    score += 1;
  }

  if (!/\d/.test(password)) {
    feedback.push('密码需要包含数字');
  } else {
    score += 1;
  }

  if (!/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
    feedback.push('密码需要包含特殊字符');
  } else {
    score += 1;
  }

  return {
    isValid: score >= 3,
    score,
    feedback,
  };
}

// 生成CSRF Token
export function generateCSRFToken(): string {
  const array = new Uint8Array(32);
  crypto.getRandomValues(array);
  return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
}

// 验证URL是否安全
export function isValidUrl(url: string): boolean {
  try {
    const parsed = new URL(url);
    return ['http:', 'https:'].includes(parsed.protocol);
  } catch {
    return false;
  }
}

// 验证文件类型
export function isValidFileType(file: File, allowedTypes: string[]): boolean {
  return allowedTypes.includes(file.type);
}

// 验证文件大小
export function isValidFileSize(file: File, maxSizeInMB: number): boolean {
  const maxSizeInBytes = maxSizeInMB * 1024 * 1024;
  return file.size <= maxSizeInBytes;
}

// 生成安全的随机字符串
export function generateSecureRandomString(length: number): string {
  const chars =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const array = new Uint8Array(length);
  crypto.getRandomValues(array);
  return Array.from(array, byte => chars[byte % chars.length]).join('');
}

// Rate Limiting 简单实现
class RateLimiter {
  private requests: Map<string, number[]> = new Map();

  public isAllowed(
    identifier: string,
    maxRequests: number,
    windowMs: number
  ): boolean {
    const now = Date.now();
    const windowStart = now - windowMs;

    // 获取当前标识符的请求记录
    const requestTimes = this.requests.get(identifier) || [];

    // 过滤掉超出时间窗口的请求
    const validRequests = requestTimes.filter(time => time > windowStart);

    // 检查是否超过限制
    if (validRequests.length >= maxRequests) {
      return false;
    }

    // 添加当前请求
    validRequests.push(now);
    this.requests.set(identifier, validRequests);

    return true;
  }

  public reset(identifier: string): void {
    this.requests.delete(identifier);
  }
}

export const rateLimiter = new RateLimiter();

// Content Security Policy 配置
export const CSP_DIRECTIVES = {
  'default-src': ["'self'"],
  'script-src': [
    "'self'",
    "'unsafe-inline'", // 开发环境需要，生产环境应移除
    'https://www.google-analytics.com',
    'https://www.googletagmanager.com',
  ],
  'style-src': ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],
  'font-src': ["'self'", 'https://fonts.gstatic.com'],
  'img-src': ["'self'", 'data:', 'https:'],
  'connect-src': ["'self'", process.env.NEXT_PUBLIC_API_BASE_URL || ''],
  'frame-ancestors': ["'none'"],
  'object-src': ["'none'"],
  'base-uri': ["'self'"],
};
